package wechat

import (
	"baokaobang/utils"
	"encoding/json"
	"fmt"
)

type AppUserInfo struct {
	AccessToken string `json:"access_token"`
	Openid      string `json:"openid"`
}

type AppUserInfoRes struct {
	Errcode    int    `json:"errcode"`
	Errmsg     string `json:"errmsg"`
	Openid     string `json:"openid"`
	Nickname   string `json:"nickname"`
	Sex        int    `json:"sex"`
	Headimgurl string `json:"headimgurl"`
	Unionid    string `json:"unionid"`
}

func NewAppUserInfo(token, openid string) *AppUserInfo {
	return &AppUserInfo{
		AccessToken: token,
		Openid:      openid,
	}
}

// APP微信登录获取用户信息
func (a *AppUserInfo) Get() (*AppUserInfoRes, error) {
	url := fmt.Sprintf(
		"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s",
		a.AccessToken, a.Openid)
	res, err := utils.GetRequest(url)
	if err != nil {
		return nil, err
	}
	var data AppUserInfoRes
	if err := json.Unmarshal(res, &data); err != nil {
		return nil, err
	}
	return &data, nil
}
